﻿using DoNet.Bpmn.Core.Enums;
using DoNet.Bpmn.Core.Utils;
using DoNet.Bpmn.Core.Vo;

namespace DoNet.Bpmn.Adaptor.BpmnElement
{
    public class BpmnElementRoleAdaptor : BpmnElementAdaptor
    {
        protected override BpmnConfCommonElementVo? GetElementVo(BpmnNodePropertysVo? property, BpmnNodeParamsVo? nodeParamsVo, int elementCode, string elementId)
        {
            int? signType = null;
            if (property != null)
            {
                signType = property.SignType;
            }

            if (nodeParamsVo != null)
            {
                List<BpmnNodeParamsAssigneeVo> assigneeList = nodeParamsVo.AssigneeList;
                if (assigneeList.Any())
                {
                    // Get the element name from the first assignee
                    string elementName = assigneeList.FirstOrDefault()?.ElementName ?? string.Empty;

                    // Create the assignee map while ensuring there is no duplication
                    var assigneeMap = nodeParamsVo.AssigneeList
                        .Where(o => o.IsDeduplication == 0)
                        .ToDictionary(
                            assigneeVo => assigneeVo.Assignee,
                            assigneeVo => assigneeVo.AssigneeName,
                            StringComparer.OrdinalIgnoreCase);

                    // Determine the sign type and call the appropriate method
                    string collectionName = "roleUserList";
                    string elementCodeStr = string.Join(collectionName, elementCode);

                    if (!string.IsNullOrEmpty(elementName))
                    {
                        if (signType == (int)SignTypeEnum.SIGN_TYPE_SIGN)
                        {
                            return BpmnElementUtils.GetMultiplayerSignElement(elementId, elementName, elementCodeStr, assigneeMap.Keys.ToList(), assigneeMap);
                        }
                        else
                        {
                            return BpmnElementUtils.GetMultiplayerOrSignElement(elementId, elementName, elementCodeStr, assigneeMap.Keys.ToList(), assigneeMap);
                        }
                    }
                }
            }
            return default;
        }

        public override void SetSupportBusinessObjects()
        {
            ((IAdaptorService)this).AddSupportBusinessObjects(NodePropertyEnum.NODE_PROPERTY_ROLE);
        }
    }
}
